package com.taxi.comm.server.mina.filter;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import net.sf.json.JsonConfig;
import net.sf.json.processors.JsonValueProcessor;

import org.apache.commons.lang.StringUtils;

public class JsonDateValueProcess implements JsonValueProcessor {

	public final static String DEFAULT_DATEFORMAT = "yyyyMMddHHmmss";

	private String format;
	private DateFormat dateFormat;

	public JsonDateValueProcess(String format) {
		this.format = format;
	}

	public JsonDateValueProcess() {
		this(DEFAULT_DATEFORMAT);
	}

	@Override
	public Object processArrayValue(Object value, JsonConfig jsonConfig) {
		return process(value, jsonConfig);
	}

	@Override
	public Object processObjectValue(String key, Object value,
			JsonConfig jsonConfig) {
		return process(value, jsonConfig);
	}

	private DateFormat getDateFormat() {
		if (dateFormat == null) {
			if (StringUtils.isEmpty(format)) {
				dateFormat = new SimpleDateFormat(DEFAULT_DATEFORMAT);
			} else {
				dateFormat = new SimpleDateFormat(format);
			}
		}

		return dateFormat;
	}

	private Object process(Object value, JsonConfig jsonConfig) {
		if (value == null) {
			return "";
		} else if (value instanceof Date) {
			return getDateFormat().format((Date) value);
		} else {
			return value.toString();
		}
	}

}
